<template>
  <div class="purchaseOrderList">
    <div class="headerTop">
      <jc-button
        :btn-arr="['reload', 'remove', 'pass', 'sub', 'push',!list.length && 'check',
                   'option', 'config', 'pushOrder', 'batchFill']"
        :disab-arr="['using', 'cancel', 'freeze']"
        url="tPurPoorder/queryPoorderLists"
        :fbillno="fbillNo"
        config="T_PUR_POORDER"
        @refresh="handleGetUntreated"
        @submit="submit(1)"
        @noSubmit="submit(2)"
        @audit="audit(1)"
        @noAudit="audit(2)"
        @toExcel="handleExport"
        @del="delectHandle"
        @forbidden="using(1)"
        @startUsing="using(2)"
        @handleCom1="queryReportForm2(1)"
        @handleCom2="queryReportForm2(2)"
        @pushOrder="pushOrder"
        @pushDown="pushDown"
        @check="check('up')"
        @check1="check('down')"
      />
    </div>
    <div class="header">
      <div class="header-name">
        <search
          :options="selectData"
          :search-son="searchSon"
          :msg="tacitly"
          @seek="collect"
          @hand="handleQuerySonClass"
        />
        <el-button type="primary" class="btn" size="mini" @click="handleQuerySonClass">{{ $t('btn.search') }}</el-button>
        <filtration
          :ftype="ftype"
          :msg="tacitly"
          :select-data="selectData"
          :table-header="tableHeader1"
          :detail-header="tableHeader"
          @seachData="handleQuerySonClass"
        />
      </div>
    </div>
    <div class="table-content">
      <jc-table
        v-loading="loading"
        :table-data="tableData"
        :table-header="tableHeader"
        :table-height="tableHeight"
        table-selection
        sortable
        get-row-keys="fentryId"
        :get-summaries="getSummaries"
        show-summary
        @selectionChange="selectionData"
        @clickRow="editParticulars"
      >
        <template v-slot:tagSlot="col">
          <el-link type="primary" @click="editParticulars(col.scope.row)">{{ col.scope.row.fbillNo }}</el-link>
        </template>
        <!--    物料编码    -->
        <template v-slot:orderSlot="col">
          <el-link type="primary" @click="jumpMateriel(col.scope.row)">
            {{ col.scope.row.fnumber }}
          </el-link>
        </template>
        <template v-slot:billSlot="clo">
          <el-tag v-if="clo.scope.row.fcloseStatus==='A'">{{ $t('market.normal') }}</el-tag>
          <el-tag v-else-if="clo.scope.row.fcloseStatus==='B'" type="danger">{{ $t('market.closed') }}</el-tag>
        </template>
        <template v-slot:text2Slot="clo">
          <el-tag v-if="clo.scope.row.fgiveaway==='1'">{{ $t('market.yes') }}</el-tag>
          <el-tag v-else-if="clo.scope.row.fgiveaway==='0'" type="danger">{{ $t('market.no') }}</el-tag>
        </template>
        <template v-slot:btnState="col">
          <span v-if="col.scope.row.fdocumentStatus === ''" />
          <el-tag v-else :type="col.scope.row.stateColor">{{ col.scope.row.fdocumentStatus }}</el-tag>
        </template>
        <!--领料状态-->
        <template v-slot:text3Slot="col">
          <span v-if="col.scope.row.fpickstatus === ''" />
          <el-tag v-else :type="col.scope.row.pickColor">{{ col.scope.row.fpickstatus }}</el-tag>
        </template>
      </jc-table>
      <cardTab @search="handleQueryBomList1" />
    </div>
    <!--    分页器-->
    <div class="footer">
      <jc-pagination
        :total="total"
        :page.sync="currentPage"
        :limit.sync="size"
        @pagination="handleGetUntreated"
      />
    </div>
    <!--  下推弹窗  -->
    <el-dialog
      v-dialogDrag
      :title="$t('market.checkBill')"
      model
      :visible.sync="isdanjuDialog"
      :close-on-click-modal="false"
      width="600px"
      top="5vh"
      center
      append-to-body
    >
      <div style="text-align: center;height: 100px;line-height: 100px">
        <el-radio-group v-model="orderLX">
          <el-radio v-for="item in receipts" :key="item" :label="item">
            {{ item }}
          </el-radio>
        </el-radio-group>
      </div>
      <hr>
      <div style="text-align: center;">
        {{ $t('market.rule') }}
        <el-input v-model="convert" size="mini" disabled style="width: 178px;margin-bottom: 5px;" />
        <br>
        {{ $t('market.billType') }}
        <el-select
          v-model.trim="fbillTypeId"
          size="mini"
          filterable
          disabled
        >
          <el-option
            v-for="(item, index) in billTypeData"
            :key="index"
            :label="item.fname"
            :value="item.fid"
          />
        </el-select>
      </div>
      <div style="text-align: center;height: 50px;padding: 20px 0;">
        整单合并:
        <el-checkbox v-model="fmerge" style="line-height: 28px">全部分录行一并下推</el-checkbox><br>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="isdanjuDialog = false">{{ $t('btn.cancel') }}</el-button>
        <el-button size="mini" type="primary" @click="pushDownOrder()">
          {{ $t('btn.confirm') }}
        </el-button>
      </span>
    </el-dialog>
    <upDown v-if="upDownVis" :msg="cha" :fentryid="fentryData" @client="upDownVis=false" />
  </div>
</template>

<script>
import {
  purPooAudit,
  purPooAuSubmit, purPooDelete,
  purPooSubmit, purPooUnAudit,
  queryPoorderLists, purPushSal,
  purPooClose, purPooUnClose
} from '@/api/purchaseManagement/purchaseOrder'
import search from '@/components/Search'
import filtration from '@/components/filtration'
import searData from '@/components/Search/mixin'
import { shut, toMxAmina, toPickStues } from '@/components/ToMxamineState'
import { maxDecimal } from '@/utils/number'
import { export_json_to_excel, formatJson } from '@/utils/Export2Excel'
import jcButton from '@/components/Button'
import { queryViewItem } from '@/api/marketManage/marketOrder'
import { insertStkStock, pushPurCheck } from '@/api/purchaseManagement/apply'
export default {
  components: {
    cardTab: () => import('@/components/cardTab'),
    upDown: () => import('@/components/upDown'),
    search,
    jcButton,
    filtration
  },
  mixins: [searData],
  props: {
    list: {
      type: Array,
      default: function() {
        return []
      }
    }
  },
  data() {
    return {
      upDownVis: false,
      cha: '',
      fbillNo: '',
      ftype: 22,
      total: 0, // 总条目
      currentPage: 1, // 当前页
      size: 200, // 每页显示多少条数据
      selectVal: [], // 多选
      fentryData: [],
      isdanjuDialog: false,
      orderLX: this.$t('menu.storageTong'),
      receipts: [this.$t('menu.storageTong'), this.$t('menu.qualityOrder')], // 生产'采购入库单''品质检验单'
      fbillTypeId: 173,
      convert: this.$t('market.cgddzrk'),
      fmerge: false,
      billTypeData: [], // 采购订单单据
      // 表头
      tableBorder: false,
      tableData: [], // 销售数据
      tableHeader: [
        { label: this.$t('market.billNo'), type: 'tag', prop: 'fbillNo', width: '120' },
        { label: this.$t('market.purchaseDate'), prop: 'fdate', width: '90' },
        { label: this.$t('market.suppliername'), prop: 'fsupplier', align: 'left', width: '160' },
        { label: this.$t('market.state'), type: 'state', prop: 'fdocumentStatus', width: '80' },
        { label: this.$t('market.closeState'), type: 'bill', prop: 'fcloseStatus', width: '80' },
        { label: this.$t('market.paezText1'), prop: 'fpaeztext', width: '110' },
        { label: this.$t('market.fmodel'), prop: 'fmodel' },
        { label: this.$t('market.fmaterial'), type: 'order', prop: 'fnumber', width: '110' },
        { label: this.$t('shop.fname2'), prop: 'fname', minWidth: '100' },
        { label: this.$t('market.productmodel'), prop: 'fproductmodel', minWidth: '100' },
        { label: this.$t('shop.fspecificaTion'), prop: 'fspecificaTion', width: '110' },
        { label: this.$t('market.funit'), prop: 'funit', width: '80' },
        { label: this.$t('market.fqty'), prop: 'fqty', align: 'right', width: '80' },
        { label: this.$t('market.ftaxPrice'), prop: 'ftaxprice', align: 'right', width: '80' },
        { label: this.$t('market.billallamount'), prop: 'fallamount', align: 'right', width: '80' },
        { label: this.$t('market.billamount'), prop: 'famount', align: 'right', width: '80' },
        { label: this.$t('market.stockQty'), prop: 'fbaseqty', align: 'right', width: '80' },
        { label: this.$t('market.stockUnit'), prop: 'fstockunit', width: '80' },
        { label: this.$t('market.instockqty'), prop: 'fstockinqty', align: 'right', width: '100' },
        { label: this.$t('market.consignDate'), prop: 'fdeliverydate', width: '90' },
        { label: this.$t('market.pickstatus'), type: 'text3', prop: 'fpickstatus', width: '80' },
        { label: this.$t('market.creator'), prop: 'fcreator', width: '80' },
        { label: this.$t('market.note'), prop: 'fnote' },
        { label: this.$t('market.fisFree'), type: 'text2', prop: 'fgiveaway' },
        { label: this.$t('market.srcbillcode'), prop: 'fsrcbillcode', width: '120' },
        { label: this.$t('market.fdescripTion'), prop: 'fdescripTion', minWidth: '200' }
      ],
      tableHeight: '70vh',
      val: [],
      fidsData: [],
      tableHeader1: [
        { label: this.$t('market.staff'), prop: 'fpurchaser' },
        { label: this.$t('market.createDate'), prop: 'fcreateDate' },
        { label: this.$t('market.modifier'), prop: 'fmodifier' },
        { label: this.$t('market.modifyDate'), prop: 'fmodifyDate' },
        { label: this.$t('market.approver'), prop: 'fapprover' },
        { label: this.$t('market.approveDate'), prop: 'fapproveDate' },
        { label: this.$t('market.localCurr'), prop: 'flocalcurr' },
        { label: this.$t('market.settleCurr'), prop: 'fsettlecurr' },
        { label: this.$t('market.settleType'), prop: 'fsettletype' },
        { label: this.$t('market.exchangeRate'), prop: 'fexchangerate' },
        { label: this.$t('market.exchangeType'), prop: 'fexchangetype' },
        { label: this.$t('market.priceList'), prop: 'fpricelist' },
        { label: this.$t('market.ftaxRate'), prop: 'ftaxrate' },
        { label: this.$t('market.billtaxamount'), prop: 'fbilltaxamount' },
        { label: this.$t('market.billtaxamount_lc'), prop: 'fbilltaxamount_lc' },
        { label: this.$t('market.billamount'), prop: 'fbillamount' },
        { label: this.$t('market.billamount_lc'), prop: 'fbillamount_lc' },
        { label: this.$t('market.billallamount_lc'), prop: 'fbillallamount_lc' }
      ]
    }
  },
  watch: {
    orderLX: {
      handler(val) {
        if (val === this.$t('menu.storageTong')) {
          this.fbillTypeId = this.fbillTypeId || 173
          if (this.fbillTypeId === 185) {
            this.fbillTypeId = 173
          }
          this.convert = this.$t('market.cgddzrk') // '采购订单至采购入库单'
          this.purpoorder()
        } else if (val === this.$t('menu.qualityOrder')) {
          this.fbillTypeId = 185
          this.convert = this.$t('market.cgddzjy') // '采购订单至品质检验单'
          this.isdanjuDialog && this.purpoorder1()
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.handleGetUntreated()
    this.tableHeader1 = this.tableHeader.concat(this.tableHeader1)
    this.tableHeight = window.innerWidth > 1440 ? 'calc(100vh - 230px)' : '70vh'
  },
  methods: {
    // 导出表格
    handleExport() {
      require.ensure([], () => {
        const tHeader = this.tableHeader.map((res) => {
          return res.label
        })
        const filterVal = this.tableHeader.map((res) => {
          return res.prop
        })
        if (this.tableData.length <= 0) {
          this.$message.warning('没有导出数据')
        } else if (this.exportVal && this.exportVal.length > 0) {
          const list = this.exportVal.map(item => {
            return shut(item)
          })
          const data = formatJson(filterVal, list)
          export_json_to_excel(tHeader, data, '采购订单列表')
        } else {
          queryPoorderLists({
            pageNum: 1,
            pageSize: 100000,
            search: this.searCollData
          }).then(res => {
            if (res.code === 0) {
              const list = res.data.array.map(item => {
                return (toMxAmina(item), shut(item), toPickStues(item))
              })
              const data = formatJson(filterVal, list)
              export_json_to_excel(tHeader, data, '采购订单列表')
            } else {
              this.$confirm(res.message, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'error'
              })
            }
          })
        }
      })
    },
    // 获取销售价目列表数据
    async handleGetUntreated(ev) {
      this.loading = true
      this.details = []
      if (ev && !ev.page) {
        this.details = ev
      }
      const DATA = {
        list: this.list,
        pageNum: this.currentPage,
        pageSize: this.size,
        search: this.searCollData.concat(this.details)
      }
      const { data: RES, data: total } = await queryPoorderLists(DATA)
      this.tableData = RES.array.map(item => {
        item.fprice = maxDecimal(item.fprice)
        return (toMxAmina(item), toPickStues(item))
      })
      this.total = total.total
      this.loading = false
    },
    // 搜索
    handleQuerySonClass(ev) {
      this.currentPage = 1
      if (ev && ev.fname) {
        this.searchSon = ev.detail
        this.customHandle(ev)
        this.handleGetUntreated(ev.detail)
      } else {
        this.handleGetUntreated()
      }
    },
    // 成品 原材料
    handleQueryBomList1(ev) {
      this.searCollData = []
      this.pageNum = 1
      this.searCollData = ev
      this.searchSon = ev
      this.handleGetUntreated()
    },
    // 价目详情
    editParticulars(ev) {
      const id = ev.fid
      this.$router.push({ path: `/editPurchase/${id}` })
    },
    // 多选 - 删除
    // 多选时触发的事件
    selectionData(val) {
      if (val[0].fsrcbilltype === 'T_PUR_REQUISITION') {
        this.fbillTypeId = 173
      } else if (val[0].fsrcbilltype === 'T_SUB_REQORDER') {
        this.fbillTypeId = 174
      }
      this.exportVal = val
      this.selectVal = []
      this.fentryData = []
      this.fidsData = []
      this.supplid = []
      this.fbillNo = val[0].fbillNo
      if (val.length > 0) {
        val.forEach(res => {
          res.fbillNo && this.selectVal.push(res.fbillNo)
          this.fentryData.push(res.fentryId)
          this.fidsData.push(res.fid)
          res.fsupplier && this.supplid.push(res.fsupplier)
        })
        this.supplid = Array.from(new Set(this.supplid))
        this.fidsData = Array.from(new Set(this.fidsData))
      }
    },
    // 下推
    pushDown() {
      this.isdanjuDialog = true
    },
    check(ev) {
      if (this.fentryData.length === 0) return
      this.cha = ev
      this.upDownVis = true
    },
    // 采购订单单据
    async purpoorder() {
      const { data: RES } = await queryViewItem({ viewName: 'SX_STK_INSTOCK' })
      this.billTypeData = RES.list
    },
    // 品质检验订单单据
    async purpoorder1() {
      const { data: RES } = await queryViewItem({ viewName: 'SX_CHECKOUT' })
      this.billTypeData = RES.list
    },
    // 下推采购入库单
    pushDownOrder() {
      if (this.orderLX === this.$t('menu.storageTong')) {
        const DATA = {
          SoucrceIds: this.fidsData,
          EntryIds: this.fentryData,
          fbillTypeId: this.fbillTypeId,
          fmerge: this.fmerge
        }
        insertStkStock(DATA).then(res => {
          if (res.code === 0) {
            this.$router.push({
              path: `/editStorage/${res.data}`
            })
            this.isdanjuDialog = false
          } else {
            this.$confirm(res.message, '提示', {
              dangerouslyUseHTMLString: true,
              confirmButtonText: '确定',
              type: 'error'
            })
          }
        })
      } else if (this.orderLX === this.$t('menu.qualityOrder')) {
        const DATA = {
          SoucrceIds: this.fidsData,
          EntryIds: this.fentryData,
          fbillTypeId: this.fbillTypeId
        }
        pushPurCheck(DATA).then(res => {
          if (res.code === 0) {
            this.$router.push({
              path: `/qualityDetail/${res.data}`
            })
            this.isdanjuDialog = false
          } else {
            this.$confirm(res.message, '提示', {
              dangerouslyUseHTMLString: true,
              confirmButtonText: '确定',
              type: 'error'
            })
          }
        })
      }
    },
    // 公共函数
    toExamineFun(api) {
      const DATA = { Numbers: this.selectVal }
      api(DATA).then(res => {
        if (res.code !== 0) {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
          return
        }
        this.handleGetUntreated()
        this.selectVal = []
        this.innerHTM = ''
        res.data.forEach(res => {
          this.innerHTM += '<div>' + res + '</div>'
        })
        this.$notify.warning({
          title: '提示',
          message: this.innerHTM,
          duration: 3000, offset: 50,
          dangerouslyUseHTMLString: true
        })
      })
    },
    // 提交
    submit(ev) {
      const api = ev === 1 ? purPooSubmit : purPooAuSubmit
      this.toExamineFun(api)
    },
    // 审核
    audit(ev) {
      const api = ev === 1 ? purPooAudit : purPooUnAudit
      this.toExamineFun(api)
    },
    // 禁用
    using(ev) {
      const api = ev === 1 ? purPooClose : purPooUnClose
      this.toExamineFun(api)
    },
    // 删除采购订单
    delectHandle() {
      this.$confirm('确定要删除么？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        const api = purPooDelete
        this.toExamineFun(api)
      })
    },
    // 套打 连打
    queryReportForm2(ev) {
      const FNUMBER = this.selectVal.join(',')
      if (ev === 1) {
        this.$router.push({ path: `/purOrderAsi1/${FNUMBER}` })
      } else {
        this.$router.push({ path: `/purOrderLianDa1/${FNUMBER}` })
      }
    },
    // 推送至惠州杰希销售订单
    pushOrder() {
      const DATA = { Numbers: this.selectVal }
      purPushSal(DATA).then(res => {
        if (res.code === 0) {
          this.$message({ showClose: true, message: res.message, type: 'success' })
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 自定义列表
    customHandle(ev) {
      this.tableHeaders = []
      if (ev.header) {
        ev.header.forEach(item => {
          this.tableHeader1.forEach(res => {
            if (res.label === item) {
              this.tableHeaders.push(res)
            }
          })
        })
        this.tableHeader = this.tableHeaders
      } else if (ev.fname === '缺省方案') {
        this.tableHeader = this.oldTabHeader
      } else {
        this.tableHeader = this.tableHeader1
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.purchaseOrderList {
  @include listBom;
  .headerTop {
    display: flex;
  }
  .el-tag {
    height: 20px;
    line-height: 20px;
  }
  .header{
    position:relative;
    .header-name{
      width: 100%;
    }
    .btn{
      transform: translateY(18%);
      margin-left: 450px !important;
    }
  }
}
</style>
